var select2;
$(function () {
    select2 = $('.select2').select2()
    var columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'id',
            title: 'id',
            visible:false
        },
        {
            field: 'name',
            title: '姓名'
        },
        {
            field: 'loginName',
            title: '登录账号'
        },
        {
            field: 'mobile',
            title: '手机'
        },
        {
            field: 'createTime',
            title: '创建时间'
        }, {
            field: 'id',
            title: '操作',
            formatter: function (value, row, index) {
                return '<button id="btn_edit" type="button" class="btn btn-primary  btn-xs" onclick="update(\'' + value + '\')"><i class="fa fa-edit"></i> 修改</button>'+
                    '<button type="button" class="btn btn-danger  btn-xs" onclick="deletes(\'' + value + '\')" style="margin-left: 10px;"><i class="fa fa-trash-o"></i> 删除</button>';
            }
        }
    ]
    createBootstrapTable($("#table"), '/admin/sysUser/info', columns, true, toolbar, 'server')
    initTree('/admin/sysDept/zTreeNodes')

})

function openDeptTree() {
    openTree($("#zTree"),"parentId","parentName");
}

// 清空表单
function clearForm() {
    // $("#loginName").val("")
    // $("#password").val("")
    // $("#remarks").val("")
    // $("#parentName").val("")
    // $("#parentId").val("")
    document.getElementById("form").reset()
}

function loadRole(res) {
    request('/admin/sysRole/info', 1, null, function (data) {
        $("#typeck").empty()
        for (var i = 0; i < data.length; i++) {
            $("#typeck").append(
                '<input type="checkbox" name="role" class="minimal" value=' + data[i].id + '><span>' + data[i].name + ''
            )
        }
        if (res != undefined) {
            $.each($('input[name=role]'), function () {
                for (var j = 0; j < res.length; j++) {
                    if (res[j] == $(this).val()) {
                        $(this).prop("checked", true);
                    }
                }
            });
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}

function getPost(res) {

    var data = {
        status: 0
    }

    request('/admin/sysPost/info', 1, data, function (data) {
        $("#postId").empty()
        for (var i = 0; i < data.length; i++) {
            $("#postId").append(
                ' <option value="' + data[i].id + '">' + data[i].postName + '</option>'
            )
        }

        if (res != undefined && res != null) {
            // select2.val(res.id).trigger('change')
            // select2.change()
            $("#postId").val(res.id).trigger('change');
        }

    }, function (error) {
        layer.msg("获取岗位信息异常！")
    })
}

function getPosition(res) {

    var data = {
        status: 0
    }

    request('/admin/sysPosition/info', 1, data, function (data) {
        $("#positionId").empty()
        for (var i = 0; i < data.length; i++) {
            $("#positionId").append(
                ' <option value="' + data[i].id + '">' + data[i].positionName + '</option>'
            )
        }

        if (res != undefined && res != null) {
            // select2.val(res.id).trigger('change')
            // select2.change()
            $("#positionId").val(res).trigger('change');
        }

    }, function (error) {
        layer.msg("获取职位信息异常！")
    })
}

var userForm;

//点击新增事件控制
function add() {
    clearForm()
    userForm = layer.open({
        type: 1,
        area: (window.innerWidth>992)? "600px":"auto",
        title: '新增',
        shade: 0.6,
        shadeClose: true, //点击遮罩关闭层
        maxmin: false,
        anim: 1,
        content: $("#user_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        } ,end:function () {
            $("#user_form").hide()
        }
    });
    loadRole()
    getPost()
    getPosition()
}

//新增用户
function save() {
    var id = $("#userId").val()
    var name = $("#name").val()
    var mobile = $("#mobile").val()
    var loginName = $("#loginName").val();
    var password = $("#password").val();
    var remarks = $("#remarks").val();
    var deptId = $("#parentId").val();
    var postId = $("#postId").val();
    var positionId = $("#positionId").val();
    var sort = $("#sort").val();
    if (loginName == '' || loginName == null) {
        layer.msg("请输入名称！")
        return
    }

    var ids = []
    $.each($('input[name=role]:checked'), function () {
        ids.push($(this).val())
    });

    if (ids.length < 1) {
        layer.msg("请至少分配一个角色    ！")
        return;
    }

    var data = {
        id: id,
        name:name,
        mobile:mobile,
        loginName: loginName,
        password: password,
        remarks: remarks,
        deptId: deptId,
        postId: postId,
        positionId: positionId,
        sort:sort,
        rids: ids.toString()
    }
    request('/admin/sysUser/save', 1, data, function (res) {
        if (res.code == 0) {
            layer.close(userForm)
            layer.msg("保存成功", {time: 1000}, function () {
                // onLoads($("#href").val())
                location.reload();
            })
        } else {
            layer.msg(res.msg, {time: 1000, icon: 5})
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}

//查询当前用户数据进行修改
function update(id) {
    clearForm()
    var data = {
        id: id
    }
    request('/admin/sysUser/update', 0, data, function (data) {
        $("#userId").val(data.data.data.id);
        $("#name").val(data.data.data.name);
        $("#mobile").val(data.data.data.mobile);
        $("#loginName").val(data.data.data.loginName);
        $("#sort").val(data.data.data.sort);
        $("#remarks").val(data.data.data.remarks);
        $("#parentId").val(data.data.sysDept.id);
        $("#parentName").val(data.data.sysDept.deptName);

        loadRole(data.data.ids)
        getPost(data.data.sysPost)
        getPosition(data.data.data.positionId)
    }, function (error) {
        layer.msg("系统异常！")
    })
    userForm = layer.open({
        type: 1,
        area: (window.innerWidth>992)? "600px":"auto",
        title: '修改',
        shade: 0.6,
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        anim: 1,
        content: $("#user_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        },end:function () {
            $("#user_form").hide()
        }
    });
}

function deletes(id) {
    var ids = [];
    if (id != undefined) {
        ids.push(id)
    } else {
        $.each($('tbody input:checkbox:checked'), function () {
            ids.push($(this).parents('tr').data('uniqueid'));
        });
    }
    if (ids.length < 1) {
        layer.msg("最少请选择一条数据！")
        return;
    }
    var data = {
        ids: ids.toString()
    }

    layer.confirm('确定删除吗？', {
        title:'提示',btn: ['取消', '确定'] //按钮
    }, function () {
        layer.close(layer.index)
    }, function () {
        request('/admin/sysUser/delete',1, data, function (data) {
            if (data.code != -1) {
                layer.msg("删除成功", {time: 1000}, function () {
                    // onLoads($("#href").val())
                    location.reload();
                })
            } else {
                layer.msg(data.msg, {time: 1000, icon: 5})
            }
        }, function (error) {
            layer.msg("系统异常！")
        })
    });


}


function formSearch() {
    var name = $("#userName").val()
    var loginName = $("#loginName1").val()

    var data = {
        name: name,
        loginName: loginName
    }
    var opt = {
        url: '/admin/sysUser/info',
        silent: true,
        query: data
    };
    $("#table" ).bootstrapTable('refresh', opt);

    //
    //
    // request('/sysUser/info', 1, data, function (res) {
    //     $("#table").bootstrapTable('load', res);
    // }, function (error) {
    //     layer.msg(error.msg)
    // })
}

function restForm() {
    document.getElementById("searchForm").reset()
    formSearch();
}



